import { createSlice } from "@reduxjs/toolkit";
import axios from "axios";
const foodsStore = createSlice({
    name:"foods",
    initialState:{
        //商品列表
        foodsList:[],
        //菜单激活下标值
        activeIndex:0,
        //购物车列表
        cartList:[],

    },
    reducers:{
        //设置商品列表
        setFoodsList(state,action){
            state.foodsList = action.payload
        },
        //设置菜单激活下标值
        setActiveIndex(state,action){
            state.activeIndex = action.payload
        },
        //添加购物车
        addCart(state,action){
            //1.判断购物车中是否存在该商品
            const item = state.cartList.find(item => item.id === action.payload.id)
            if(item){
                //存在
                item.count++
            }else{
                //不存在
                state.cartList.push(action.payload)
                console.log(state.cartList,'state.cartList')
            }
            // const index = state.cartList.findIndex(item => item.id === action.payload.id)
            // if(index === -1){
            //     //不存在
            //     state.cartList.push(action.payload)
            // }else{
            //     //存在
            //     state.cartList[index].count++
            // }
        },
        //count增加
        increment(state,action){
            const item = state.cartList.find(item => item.id === action.payload.id)
            item.count++
        },
        //count减少
        decrement(state,action){
            const item = state.cartList.find(item => item.id === action.payload.id)
            if(item.count === 1){
                //删除
                state.cartList = state.cartList.filter(item => item.id !== action.payload.id)
            }else{
                //减少
                item.count--
            }
        },
        //清空购物车
        clearCart(state,action){
            state.cartList = []
        }
    }
})
const {setFoodsList,setActiveIndex,addCart,increment,decrement,clearCart} = foodsStore.actions;

//异步获取部分
const fetchFoodsList = () => {
  return async (dispatch) => {
    const res = await axios.get("http://localhost:3004/takeaway");
    console.log(res,'store中的res');
    dispatch(setFoodsList(res.data));
    }
}

export {fetchFoodsList,setActiveIndex,addCart,increment,decrement,clearCart}

const reducer = foodsStore.reducer;

export default reducer;